<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="路由名称" style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.menuName" placeholder="菜单名称" style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.permission" placeholder="权限标识" style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.type" clearable placeholder="请选择" style="width: 100px;" class="filter-item" @change="handleFilter">
        <el-option label="菜单" value="1" />
        <el-option label="权限" value="2" />
      </el-select> -->
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" @click="handleFilter">
        <svg-icon icon-class="search" /> 搜索
      </el-button>
      <el-button v-permission="['p_menu_insert']" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">
        <svg-icon icon-class="add" /> 添加主菜单
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      ref="multipleTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-key="getRowKey"
      :expand-row-keys="expandRows"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @sort-change="sortChange"
      @expand-change="expandChange"
    >
      <el-table-column label="路由名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.menuName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限标识" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.permission }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜单类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type === 1">菜单</el-tag>
          <el-tag v-if="scope.row.type === 2" type="info">权限</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序值" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="checkPermission(['p_menu_insertChildren', 'p_menu_updateChilren', 'p_menu_deleteChilren'])" label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-tooltip class="item" effect="dark" content="添加子菜单" placement="top">
            <el-button v-if="row.type === 1" v-permission="['p_menu_insertChildren']" type="primary" circle @click="handleCreateChildren(row)">
              <svg-icon icon-class="add" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button v-permission="['p_menu_updateChilren']" type="primary" circle @click="(row.parentId === '0' && row.type === 1)?handleUpdate(row):(row.parentId != '0' && row.type === 1)?handleUpdateChildrenMenu(row):handleUpdateChildrenRole(row)">
              <svg-icon icon-class="edit" />
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button v-permission="['p_menu_deleteChilren']" type="danger" circle @click="handleDeleteColumn(row)">
              <svg-icon icon-class="delete" />
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="closeOnClickModal">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
        <el-form-item v-if="showName" label="路由名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="temp.menuName" />
        </el-form-item>
        <el-form-item v-if="showPermission" label="权限标识" prop="permission">
          <el-input v-model="temp.permission" />
        </el-form-item>
        <el-form-item v-if="showType" label="菜单类型" prop="type">
          <el-radio-group v-model="temp.type" @change="handleMenuTypeChange">
            <el-radio border :label="1">菜单</el-radio>
            <el-radio border :label="2">权限</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input v-model="temp.sort" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():dialogStatus==='createChildrenMenu'?createChildMenu():dialogStatus==='updateChildrenMenu'?updateChildMenu():dialogStatus==='updateChildrenRole'?updateChildrenRole():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectMenu, insertMenu, updateMenu, updateChildrenMenu, deleteMenu, validMenuName, validMenuPermission } from '@/api/menu'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'Menu',
  components: { },
  directives: { waves },
  data() {
    const validateMenuName = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('请输入路由名称'))
      }
      const menu = { id: '', name: value }
      if (this.dialogStatus === 'update' || this.dialogStatus === 'updateChildrenMenu' || this.dialogStatus === 'updateChildrenRole') {
        menu.id = this.temp.id
      }
      validMenuName(menu).then(response => {
        if (!response.data) {
          callback(new Error('路由名称重复'))
        } else {
          callback()
        }
      }).catch(err => {
        callback(new Error(err))
      })
    }
    const validateMenuPermission = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('请输入权限标识'))
      }
      const menu = { id: '', permission: value }
      if (this.dialogStatus === 'update' || this.dialogStatus === 'updateChildrenMenu' || this.dialogStatus === 'updateChildrenRole') {
        menu.id = this.temp.id
      }
      validMenuPermission(menu).then(response => {
        if (!response.data) {
          callback(new Error('权限标识重复'))
        } else {
          callback()
        }
      }).catch(err => {
        callback(new Error(err))
      })
    }
    return {
      tableKey: 0,
      list: [],
      listLoading: true,
      expandRows: [],
      listQuery: {
        name: '',
        menuName: '',
        permission: '',
        type: '',
        ids: [],
        sortable: 'asc'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      temp: {
        id: '',
        parentId: '',
        name: '',
        menuName: '',
        permission: '',
        type: '',
        sort: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改主菜单',
        create: '新增主菜单',
        createChildrenMenu: '新增子菜单',
        updateChildrenMenu: '修改子菜单',
        updateChildrenRole: '修改子权限'
      },
      rules: {
        name: [{ required: true, trigger: 'change', validator: validateMenuName }],
        menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        permission: [{ required: true, trigger: 'change', validator: validateMenuPermission }],
        type: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
      },
      downloadLoading: false,
      showPermission: true,
      showType: true,
      showName: true,
      closeOnClickModal: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true
      selectMenu(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    getRowKey(row) {
      return row.id
    },
    handleFilter() {
      this.getList()
    },
    handleDeleteColumn(row) {
      const data = { ids: [] }
      const ids = []
      ids.push(row.id)
      data.ids = ids
      this.$confirm('确定删除该菜单吗？该菜单下的子菜单也会被删除！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const response = await deleteMenu(data)
          this.getList()
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.data
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    handleMenuTypeChange(val) {
      const updateChildrenRole = !!(((this.dialogStatus === 'updateChildrenRole' || this.dialogStatus === 'updateChildrenMenu' || this.dialogStatus === 'createChildrenMenu') && val === 1))
      if (updateChildrenRole) {
        this.showName = true
      } else {
        this.showName = false
      }
    },
    expandChange(row, expanded) {
      if (expanded) {
        this.expandRows.push(row.id)
      } else {
        const closeRowId = this.expandRows.indexOf(row.id)
        this.expandRows.splice(closeRowId)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sortable = 'asc'
      } else {
        this.listQuery.sortable = 'desc'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        parentId: '',
        name: '',
        menuName: '',
        permission: '',
        type: '',
        sort: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.showName = true
      this.showPermission = false
      this.showType = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.parentId = 0
          this.temp.permission = null
          this.temp.type = 1
          insertMenu(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '新增主菜单成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleCreateChildren(row) {
      this.resetTemp()
      this.dialogStatus = 'createChildrenMenu'
      this.showName = true
      this.showPermission = true
      this.showType = true
      this.dialogFormVisible = true
      this.temp.parentId = row.id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createChildMenu() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.showName) {
            this.temp.name = null
          }
          insertMenu(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            if (this.temp.type === 1) {
              this.$notify({
                title: 'Success',
                message: '新增子菜单成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'Success',
                message: '新增子权限成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.showName = true
      this.showPermission = false
      this.showType = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.children = null
          updateMenu(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdateChildrenMenu(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'updateChildrenMenu'
      this.showName = true
      this.showPermission = true
      this.showType = true
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateChildMenu(row) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.children = null
          if (tempData.type === 2) {
            tempData.name = ''
            this.$confirm('确定修改菜单为权限吗？该子菜单下的所有菜单及权限会被删除', '警告', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(async() => {
              updateChildrenMenu(tempData).then(() => {
                this.dialogFormVisible = false
                this.getList()
                this.$notify({
                  title: 'Success',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
              })
            })
          } else {
            updateChildrenMenu(tempData).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    handleUpdateChildrenRole(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'updateChildrenRole'
      this.showName = false
      this.showPermission = true
      this.showType = true
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateChildrenRole() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateMenu(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete() {
      const data = { ids: [] }
      const colmuns = this.$refs.multipleTable.selection
      if (colmuns.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择一行菜单数据！'
        })
        return
      }
      colmuns.forEach(colmun => {
        data.ids.push(colmun.id)
      })
      this.$confirm('确定删除这些菜单吗？这些菜单下的子菜单也会被删除！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const response = await deleteMenu(data)
          this.getList()
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.data
            })
          }
        })
        .catch(err => { console.error(err) })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style>
body .el-table th.gutter{
    display: table-cell!important;
}

body .el-table colgroup.gutter{
    display: table-cell!important;
}
</style>
